package LeetCode_SingleLinkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description:翻转链表
 * User: 阿宾
 * Date: 2024-11-06
 * Time: 21:37
 */

public class Demo1 {
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public ListNode reverseList1(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode cur = head.next;//用来遍历链表
        ListNode pre = head.next;//用来帮助cur定位遍历链表的下一个节点
        head.next = null;
        while (cur != null) {
            pre = cur.next;
            cur.next = head;
            head = cur;
            cur = pre;
        }
        return head;
    }
    public static ListNode reverseList(ListNode head) {
        //初始化结点
        ListNode prev = null;//前一个节点
        ListNode current = head;//当前节点
        ListNode cur = null;//下一个节点
        while (current != null){
            cur = current.next;//保存下一个节点
            current.next = prev;//反转当前节点
            prev = current;
            current = cur;
        }
        return prev;
    }

    public static void main(String[] args) {
        // 创建链表并测试
        /*ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);*/
        ListNode head = new ListNode(12, new ListNode(23,new ListNode(56,new ListNode(5,new ListNode(3)))));
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
        ListNode reversedHead = reverseList(head);
        // 打印反转后的链表
        while (reversedHead != null) {
            System.out.print(reversedHead.val + " ");
            reversedHead = reversedHead.next;
        }
    }
}
